package com.lyn.utils;

import android.annotation.SuppressLint;
import android.util.Log;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

/**
 * @author longyn 2023/5/15
 * @version 1.0.0
 */
public class ShellUtil {

    private static final String TAG = "ShellUtil";

    public static String shell(String cmd) {
       return shell(cmd,false);
    }

    @SuppressLint("NewApi")
    public static String shell(String cmd, boolean isRead) {
        Log.d(TAG, "shell:" + cmd);
        InputStream inputStream = null;
        InputStreamReader inputStreamReader;
        BufferedReader bufferedReader = null;
        try {
            Runtime runtime = Runtime.getRuntime();
            String[] cmdS = new String[]{"sh", "-c", cmd};
            Process process = runtime.exec(cmdS);
            if (!isRead) {
                return null;
            }
            inputStream = process.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            process.waitFor(1, TimeUnit.SECONDS);
            String lineStr;
            StringBuilder sb = new StringBuilder();
            while ((lineStr = bufferedReader.readLine()) != null) {
                sb.append(lineStr).append("\n");
            }
            String result = sb.toString();
            Log.d(TAG, "shell result:" + result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }



}
